﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using BitcoinMarket.DataSources;
using BitcoinMarket.DataConnectors;
using Telerik.Windows.Controls;
using BitcoinMarket.Libs;
using BitcoinMarket.Resources;


namespace BitcoinMarket
{
    public struct VisualBoolean
    {
        private readonly static VisualBoolean True = new VisualBoolean() { isTrue = true };
        private readonly static VisualBoolean False = new VisualBoolean() { isTrue = false };
        
        private bool isTrue;

        public bool IsTrue { get { return isTrue; } }

        public bool IsFalse { get { return !IsTrue; } }

        public Visibility IsTrueVisibility
        {
            get { return IsTrue ? Visibility.Visible : Visibility.Collapsed; }
        }

        public Visibility IsFalseVisibility
        {
            get { return IsFalse ? Visibility.Visible : Visibility.Collapsed; }
        }

        public static implicit operator VisualBoolean(bool isTrue)
        {
            if (isTrue) return True;
            return False;
        }

        public static implicit operator bool(VisualBoolean visualBoolean)
        {
            return visualBoolean.isTrue;
        }
    }

    public class MainViewModel : INotifyPropertyChanged
    {
        public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> Items { get; private set; }

        public Collection<BitcoinChartsMarketsCurrencyCollection> MarketsDataCollection { get; private set; }
        //public Collection<BitcoinChartsPricesDataItem> PricesDataCollection { get; private set; }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        private VisualBoolean _IsLoading;
        public VisualBoolean IsLoading
        {
            get { return _IsLoading; }
            set
            {
                _IsLoading = value;
                RaisePropertyChanged("IsLoading");
            }
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadMarketsData()
        {
            this.IsLoading = true;
            this.Items.Clear();

            //BitcoinChartsPricesDataConnector PricesConnector = new BitcoinChartsPricesDataConnector(this.PricesDataConnectorReady); 
            BitcoinChartsMarketsDataConnector MarketsConnector = new BitcoinChartsMarketsDataConnector();
            MarketsConnector.GetMarketsData(this.MarketsDataConnectorReady);
        }

        /// <summary>
        /// Callback for the markets dataconnector
        /// </summary>
        public void MarketsDataConnectorReady(Collection<BitcoinChartsMarketsCurrencyCollection> DataColl)
        {
            if (DataColl == null && this.MarketsDataCollection != null)
            { //If the page is reloaded after chaging settings this is executed
                this.MarketsDataCollection = this.SortCurrencies(this.MarketsDataCollection);
            }
            else
            {
                this.MarketsDataCollection = this.SortCurrencies(DataColl);
            }

            //Add the parsed data into the UI component
            if (App.MainPageObj != null)
            {
                foreach (BitcoinChartsMarketsCurrencyCollection item in this.MarketsDataCollection)
                {
                    this.Items.Add(new ItemViewModel() { CurrencyName = item.Currency, H24 = item.h24 <= 0 ? "---" : item.h24.ToString(), D7 = item.d7 <= 0 ? "---" : item.d7.ToString(), D30 = item.d30 <= 0 ? "---" : item.d30.ToString() });
                }

                //Set the correct date of the shown data in the UI
                BitcoinChartsMarketsDataSource DataSrc = new BitcoinChartsMarketsDataSource(true);
                DateTime date = DataSrc.GetTMPFileLastChangeDate();

                App.MainPageObj.LabelAvgPriceOneBtc.Text = AppResources.PriceOneBitcoin.Replace("%s", date.ToShortDateString());
            }

            this.IsDataLoaded = true;
            this.IsLoading = false;
        }

        /// <summary>
        /// Sort the currencies so the user prefered one will be on the top of the list
        /// </summary>
        /// <param name="DataColl">List of currecies to sort</param>
        private Collection<BitcoinChartsMarketsCurrencyCollection> SortCurrencies(Collection<BitcoinChartsMarketsCurrencyCollection> DataColl)
        {
            Collection<BitcoinChartsMarketsCurrencyCollection> tmpColl = DataColl;
            Collection<BitcoinChartsMarketsCurrencyCollection> PreferedItems = new Collection<BitcoinChartsMarketsCurrencyCollection>();
            AppCurrencySettings settings = new AppCurrencySettings();

            //first add the topped items
            for (int i = tmpColl.Count-1; i >= 0; i--)
            {
                if (settings.GetValueOrDefault<bool>(((BitcoinChartsMarketsCurrencyCollection)tmpColl.ElementAt(i)).Currency, settings.GetToppedDefault(((BitcoinChartsMarketsCurrencyCollection)tmpColl.ElementAt(i)).Currency)))
                {
                    PreferedItems.Add((BitcoinChartsMarketsCurrencyCollection)tmpColl.ElementAt(i));
                    tmpColl.RemoveAt(i);
                }
            }

            //then add all other items
            foreach (BitcoinChartsMarketsCurrencyCollection item in tmpColl)
            {
                PreferedItems.Add(item);
            }

            return PreferedItems;
        }

        /// <summary>
        /// Loads the data shown in the "Network info" control
        /// </summary>
        public void LoadNetworkDataByKeyName(string key)
        {
            BlockChainDataConnector dc = new BlockChainDataConnector();
            dc.GetUserSelectedData(NetworkStatusChartsDataDownloaded, key);
        }

        /// <summary>
        /// Callback for the Hash Rate downloaded method
        /// </summary>
        /// <param name="data"></param>
        private void NetworkStatusChartsDataDownloaded(Collection<BlockChainChartItem> ChartsData)
        {
            //MessageBox.Show(ChartsData.ToString());
            App.ChartsAllData = ChartsData;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}